<template>
  <div class="statistics-container">
    <!-- search -->
    <el-card class="search-card" style="margin-left: auto; padding-left: 30%; padding: 0;">
      <el-form :model="searchForm" label-width="120px" @submit.prevent="loadStatistics">
        <el-row :gutter="10">
          <el-col :span="7">
            <el-form-item label="按年月查询">
              <el-date-picker
                v-model="searchForm.month"
                type="month"
                placeholder="选择年月"
                format="YYYY-MM"
                value-format="YYYY-MM"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="searchForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="searchForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align: right; display: flex; align-items: flex-end; justify-content: flex-end;">
            <div style="padding-bottom: 10px;">
              <el-button type="primary" @click="loadStatistics">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- search -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="stat-card type-stat">
          <div class="stat-content">
            <!-- <div class="stat-icon">
              <i class="el-icon-collection"></i>
            </div> -->
            <div class="stat-info">
              <div class="stat-title">运输数量</div>
              <div class="stat-number">{{ statisticsData.workDataCount }}</div>
            </div>
          </div>
          <div class="stat-actions">
            <!-- <el-button type="primary" size="small" @click="viewDetails('workData')" disabled></el-button> -->
            <text> &nbsp </text>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card driver-stat">
          <div class="stat-content">
            <!-- <div class="stat-icon">
              <i class="el-icon-user"></i>
            </div> -->
            <div class="stat-info">
              <div class="stat-title">司机人数</div>
              <div class="stat-number">{{ statisticsData.driverCount }}</div>
            </div>
          </div>
          <div class="stat-actions">
            <el-button type="primary" size="small" @click="viewDetails('driver')">查看详细</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card vehicle-stat">
          <div class="stat-content">
            <!-- <div class="stat-icon">
              <i class="el-icon-truck"></i>
            </div> -->
            <div class="stat-info">
              <div class="stat-title">钩机数量</div>
              <div class="stat-number">{{ statisticsData.excavatorCount }}</div>
            </div>
          </div>
          <div class="stat-actions">
            <el-button type="primary" size="small" @click="viewDetails('excavator')">查看详细</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card transport-stat">
          <div class="stat-content">
            <!-- <div class="stat-icon">
              <i class="el-icon-s-operation"></i>
            </div> -->
            <div class="stat-info">
              <div class="stat-title">运输车数量</div>
              <div class="stat-number">{{ statisticsData.transportCount }}</div>
            </div>
          </div>
          <div class="stat-actions">
            <el-button type="primary" size="small" @click="viewDetails('transport')">查看详细</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- <el-card class="chart-card" style="display: none;">
      <template #header>
        <div class="card-header">
          <span>按车辆类型分类统计</span>
        </div>
      </template>
      <div ref="chartRef" class="chart-container"></div>
    </el-card> -->

    <!-- Drivers Table -->
    <!-- <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>司机数据</span>
        </div>
      </template>
      <ProTable
        ref="driversTableRef"
        :request-api="getDriversListWithParams"
        :columns="driversColumns"
        :pagination="true"
        class="data-table"
      />
    </el-card> -->

    <!-- Excavators Table -->
    <!-- <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>钩机数据</span>
        </div>
      </template>
      <ProTable
        ref="excavatorsTableRef"
        :request-api="getExcavatorsListWithParams"
        :columns="excavatorsColumns"
        :pagination="true"
        class="data-table"
      />
    </el-card> -->

    <!-- Transport Vehicles Table -->
    <!-- <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>运输车数据</span>
        </div>
      </template>
      <ProTable
        ref="transportVehiclesTableRef"
        :request-api="getTransportVehiclesListWithParams"
        :columns="transportVehiclesColumns"
        :pagination="true"
        class="data-table"
      />
    </el-card> -->

    <!-- Work Data Table -->
    <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>运输数据</span>
        </div>
      </template>
      <ProTable
        ref="workDataTableRef"
        :request-api="getWorkDataListWithParams"
        :columns="workDataColumns"
        :pagination="true"
        class="data-table"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getDataStatistics, getDriversList, getExcavatorsList, getTransportVehiclesList, getWorkDataList } from '@/api/modules/datainfo/dataStatistics';
import type { DataStatisticsResult, DataStatisticsQuery } from '@/api/types/datainfo/dataStatistics';
import type { ColumnProps } from '@/components/ProTable/interface';
import ProTable from '@/components/ProTable/index.vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

defineOptions({
  name: 'DataStatistics'
});

const router = useRouter();

// 搜索表单
const searchForm = ref({
  month: '', //getCurrentMonth(),
  startTime: '',
  endTime: ''
});

// 获取当前月份的函数
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  return `${year}-${month}`;
}

// 统计数据
const statisticsData = ref<DataStatisticsResult>({
  workDataCount: 0,
  excavatorCount: 0,
  transportCount: 0,
  driverCount: 0
});

// 图表引用
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 表格引用
const driversTableRef = ref();
const excavatorsTableRef = ref();
const transportVehiclesTableRef = ref();
const workDataTableRef = ref();

// Store search parameters
let currentSearchParams: DataStatisticsQuery = {};

// Drivers table columns
const driversColumns: ColumnProps[] = [
  { prop: 'userId', label: '用户ID', width: 100 },
  { prop: 'username', label: '用户名', width: 150 },
  { prop: 'nickname', label: '昵称', width: 150 },
  { prop: 'phone', label: '手机号', width: 150 },
  { prop: 'deptName', label: '部门名称', width: 150 }
];

// Excavators table columns
const excavatorsColumns: ColumnProps[] = [
  { prop: 'vehicleId', label: '车辆ID', width: 100 },
  { prop: 'vehicleNumber', label: '车辆编号', width: 150 },
  { prop: 'title', label: '标题', width: 150 },
  { prop: 'vehicleTypeCd', label: '车辆类型代码', width: 150 },
  { prop: 'deptName', label: '部门名称', width: 150 }
];

// Transport vehicles table columns
const transportVehiclesColumns: ColumnProps[] = [
  { prop: 'vehicleId', label: '车辆ID', width: 100 },
  { prop: 'vehicleNumber', label: '车辆编号', width: 150 },
  { prop: 'title', label: '标题', width: 150 },
  { prop: 'vehicleTypeCd', label: '车辆类型代码', width: 150 },
  { prop: 'deptName', label: '部门名称', width: 150 }
];

// Work data table columns
const workDataColumns: ColumnProps[] = [
  { prop: 'id', label: 'ID', width: 100 },
  { prop: 'originalFilename', label: '原始文件名', width: 200 },
  { prop: 'newFilename', label: '作业记录文件', width: 200 },
  // { prop: 'fileType', label: '文件类型', width: 120 },
  // { prop: 'fileSize', label: '文件大小', width: 120 },
  // { prop: 'processStatusDisplay', label: '处理状态', width: 120 },
  { prop: 'carNumber', label: '车辆编号', width: 150 },
  { prop: 'driverName', label: '司机', width: 150 },
  { prop: 'fileTag', label: '设备编号', width: 150 },
  { prop: 'deptName', label: '公司车队名称', width: 150 },
  { prop: 'createTime', label: '创建时间' }
];

// API functions with search parameters
// const getDriversListWithParams = (params: any) => {
//   return getDriversList({ ...currentSearchParams, ...params });
// };

// const getExcavatorsListWithParams = (params: any) => {
//   return getExcavatorsList({ ...currentSearchParams, ...params });
// };

// const getTransportVehiclesListWithParams = (params: any) => {
//   return getTransportVehiclesList({ ...currentSearchParams, ...params });
// };

const getWorkDataListWithParams = (params: any) => {
  return getWorkDataList({ ...currentSearchParams, ...params });
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    const params: DataStatisticsQuery = {};
    
    // 如果选择了年月，使用年月查询
    if (searchForm.value.month) {
      params.month = searchForm.value.month;
    } 
    // 否则使用开始时间和结束时间查询
    else {
      if (searchForm.value.startTime) {
        params.startTime = searchForm.value.startTime;
      }
      if (searchForm.value.endTime) {
        params.endTime = searchForm.value.endTime;
      }
    }
    
    // Store the search parameters for use in table requests
    currentSearchParams = { ...params };
    
    // 获取统计数据
    const res = await getDataStatistics(params);
    statisticsData.value = res.data;
    
    // 刷新所有表格数据
    refreshAllTables();
  } catch (error) {
    ElMessage.error('获取统计数据失败');
    console.error('Failed to load statistics:', error);
  }
};

// 刷新所有表格
const refreshAllTables = () => {
  // if (driversTableRef.value) driversTableRef.value.getTableList();
  // if (excavatorsTableRef.value) excavatorsTableRef.value.getTableList();
  // if (transportVehiclesTableRef.value) transportVehiclesTableRef.value.getTableList();
  if (workDataTableRef.value) workDataTableRef.value.getTableList();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.value = {
    month: '',
    startTime: '',
    endTime: ''
  };
  loadStatistics();
};

// 组件挂载时加载数据
onMounted(() => {
  loadStatistics();
});

// 查看详细信息
const viewDetails = (type: string) => {
  console.log('View details for:', type);
  // 根据类型跳转到对应的详细页面
  let routePath = '';
  switch (type) {
    case 'workData':
      // 跳转到统计数据页面
      routePath = '/datalist/statisticsDataList';
      break;
    case 'driver':
      // 跳转到司机数据页面
      routePath = '/driversData';
      break;
    case 'excavator':
      // 跳转到钩机数据页面
      routePath = '/excavatorData';
      break;
    case 'transport':
      // 跳转到运输车数据页面
      routePath = '/transportData';
      break;
    default:
      ElMessage.warning('未知的数据类型');
      return;
  }
  // 尝试导航到路由
  router.push(routePath).catch(err => {
    console.error('Navigation failed:', err);
    ElMessage.error(`导航到${type}页面失败，请确认该页面是否存在`);
  });
};
</script>

<style scoped lang="scss">
.statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 36px;
  margin-right: 15px;
  padding: 15px;
  border-radius: 8px;
}

.stat-info {
  flex: 1;
  text-align: center;
}

.stat-title {
  font-size: 18px;
  font-weight: bold;
  color: #339af0;
  margin-bottom: 5px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.driver-stat .stat-icon {
  background-color: #eb303f;
  color: #409eff;
}

.vehicle-stat .stat-icon {
  background-color: #80e948;
  color: #67c23a;
}

.transport-stat .stat-icon {
  background-color: #d8e750;
  color: #e6a23c;
}

.type-stat .stat-icon {
  background-color: #3737f0;
  color: #909399;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.stat-actions {
  text-align: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

/* Ensure tables have a minimum height when empty */
.data-table {
  min-height: 300px;
}

.data-table:deep(.table-main) {
  min-height: 250px;
}

/* Ensure table-empty image is displayed completely */
.data-table:deep(.table-empty) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  padding: 20px;
}

.data-table:deep(.table-empty img) {
  max-width: 100%;
  max-height: 150px;
  width: auto;
  height: auto;
  object-fit: contain;
  margin-bottom: 10px;
}

.data-table:deep(.table-empty div) {
  font-size: 14px;
  color: #909399;
}
</style>